<?php

namespace App\Http\Common;


use App\Http\Controllers\Controller;
use App\Kits\Errors\NotDataException;
use App\Kits\Errors\ValidateException;
use App\Kits\Middleware\ProductMiddleware;
use App\Kits\Resources\ApiResource;
use App\Kits\Services\LibAuthService;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class DemoController extends Controller
{
    public function __construct()
    {
        // 生产环境中该控制器方法均不可用
        $this->middleware(ProductMiddleware::class);
    }

    public function demo(Request $request)
    {
        return [
            'ip' => $request->getClientIp(),
            'ips' => $request->getClientIps()
        ];
    }

    /**
     * 测试登录
     * @param Request $request
     * @return ApiResource
     * @throws \Exception
     */
    public function testLogin(Request $request)
    {
        $data = $request->all();
        if (!isset($data['mobile']) || empty($data['mobile'])) {
            throw new ValidateException('请填写手机号码');
        }
        try {
            DB::beginTransaction();
            /** @var User $user */
            $user = User::where('mobile', $data['mobile'])->first();
            if (!$user) {
                throw new NotDataException('用户不存在');
            }
            $token = LibAuthService::generateTokenByUser($user, '测试登录');
            if (isset($user->roles)) {
                unset($user->roles);
            }
            DB::commit();
            return json('登录成功', [
                "userInfo" => $user,
                "token" => $token,
            ]);
        } catch (\Exception $exception) {
            DB::rollBack();
            return errorJson($exception);
        }
    }


}
